package com.hnkywl.sts.service.base;

import com.hnkywl.sts.dao.base.WebserviceLogDao;
import com.hnkywl.sts.entity.base.WebserviceLog;
import com.hnkywl.sts.webservice.bg.util.ClientIPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-8-12
 * Time: 下午1:54
 * To change this template use File | Settings | File Templates.
 */
@Service
public class WebserviceLogService {
    private WebserviceLogDao webserviceLogDao;

    @Transactional
    public void saveServerLog(String clazz, String method, String parameterDate, String returnDate, String exception,String description) {
        //WebserviceLog log = getLog(clazz, method, parameterDate, returnDate, exception, "server");
        saveLogSql(clazz, method, parameterDate, returnDate, exception, "server",description);
    }

    @Transactional
    public void saveClientLog(String clazz, String method, String parameterDate, String returnDate, String exception,String description) {
        //WebserviceLog log = getLog(clazz, method, parameterDate, returnDate, exception, "client");
        saveLogSql(clazz, method, parameterDate, returnDate, exception, "client",description);
    }

    private void saveLogSql(String clazz, String method, String parameterDate, String returnDate, String exception, String type,String description) {
        String sql = "insert into t_sys_webservice_log(id,clazz,method,type,parameterdata,returndata,time,clientip,exception,description) " +
                "values(seq_sys_webservice_log.nextval,?,?,?,?,?,?,?,?,?)";
        String ip = "";
        if ("server".equals(type))
            ip = ClientIPUtil.getRemoteIp();
        webserviceLogDao.executeSQL(sql, clazz, method, type, parameterDate, returnDate, new Date(), ip, exception,description);
    }

    private WebserviceLog getLog(String clazz, String method, String parameterDate, String returnDate, String exception, String type, String description) {
        WebserviceLog log = new WebserviceLog();
        log.setClazz(clazz);
        log.setMethod(method);
        log.setParameterData(parameterDate);
        log.setReturnData(returnDate);
        log.setType(type);
        log.setTime(new Date());
        log.setDescription(description);
        if ("server".equals(type))
            log.setClientIP(ClientIPUtil.getRemoteIp());
        log.setException(exception);
        return log;
    }

    @Autowired
    public void setWebserviceLogDao(WebserviceLogDao webserviceLogDao) {
        this.webserviceLogDao = webserviceLogDao;
    }
}
